package com.yunze.polling.card;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.common.config.MyDictionary;
import com.yunze.common.core.card.CardChange;
import com.yunze.common.mapper.mysql.YzCardMapper;
import com.yunze.common.mapper.mysql.YzOrderMapper;
import com.yunze.common.utils.yunze.PlOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 订单卡号API执行 【开机、开网、订购达量停机】 消费者
 */
@Slf4j
@Component
public class OrdeCardDiagnosis {

    @Resource
    private MyDictionary myDictionary;
    @Resource
    private CardChange cardChange;
    @Resource
    private YzCardMapper yzCardMapper;
    @Resource
    private YzOrderMapper yzOrderMapper;
    @Resource
    private PlOrder plOrder;
    /**
     * 监听器
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "admin_orderCardDiagnosis_queue", containerFactory = "customContainerFactory")
    public void pollingStart(String msg, Channel channel_1) throws IOException {
        if (msg != null && msg.length() > 0) {
            Map<String,Object> map = JSON.parseObject(msg);
            String iccid = map.get("iccid").toString();//iccid
            List<String> operationArr = (List<String>) map.get("optionType");//诊断 操作类型
            String source_type = map.get("source_type")!=null?map.get("source_type").toString():null;//
            String quota = map.get("quota")!=null?map.get("quota").toString():null;//

            String exCount = map.get("exCount")!=null?map.get("exCount").toString():"0";//执行次数 【补偿进行重复操作】
            Map<String,Object> updOrderMap = map.get("updOrderMap")!=null?(Map<String, Object>) map.get("updOrderMap"):null;
            Diagnosis(iccid, operationArr,source_type,updOrderMap,quota,exCount);
        }
    }




    /**
     * 监听器
     * @param msg
     * @param channel_1
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "dlx_admin_orderCardDiagnosis_queue", containerFactory = "customContainerFactory")
    public void dlxpollingStart(String msg, Channel channel_1) throws IOException {
        if (msg != null && msg.length() > 0) {
            Map<String,Object> map = JSON.parseObject(msg);
            String iccid = map.get("iccid").toString();//iccid
            List<String> operationArr = (List<String>) map.get("optionType");//诊断 操作类型
            String source_type = map.get("source_type")!=null?map.get("source_type").toString():null;//
            String quota = map.get("quota")!=null?map.get("quota").toString():null;//
            String exCount = map.get("exCount")!=null?map.get("exCount").toString():"1";//执行次数 【补偿进行重复操作】

            Map<String,Object> updOrderMap = map.get("updOrderMap")!=null?(Map<String, Object>) map.get("updOrderMap"):null;//订单变更装填需要传入订单修改 参数

            Diagnosis(iccid, operationArr,source_type,updOrderMap,quota,exCount);
        }
    }




    /**
     * 诊断 消费
     * @param iccid
     * @param operationArr
     */
    public void Diagnosis(String iccid, List<String> operationArr,String source_type,Map<String,Object> updOrderMap,String quota,String exCount){
        Map<String,Object> Parammap = new HashMap<>();
        Parammap.put("iccid",iccid);
        Integer intExCount = Integer.parseInt(exCount);
        if(operationArr!=null && operationArr.size()>0){
            Map<String,Object> map = yzCardMapper.findRoute(Parammap);
            if(map!=null){
                for (int i = 0; i < operationArr.size(); i++) {
                    String OPtion = operationArr.get(i);
                    boolean bool = true;
                    switch (OPtion){
                        case "PowerOn"://开机
                            Parammap.put("Is_Stop","on");
                            bool = Open(iccid,Parammap,map,updOrderMap);
                            break;
                        case "OpenNetwork"://开网
                            Parammap.put("Is_Break","0");
                            bool = OpenConnection(iccid,Parammap,map,updOrderMap);
                            break;
                        case "InternetDisconnection"://达量断网 订购
                            Parammap.put("action","1");
                            Parammap.put("quota",quota);// 【达量断网订购 】  阈值MB
                            bool = ByInternetDisconnection(iccid,Parammap,map,source_type,updOrderMap);
                            break;
                    }
                    if(!bool && intExCount<=5){//最多 重复执行次数 默认5次 【失败后立即转发 】
                        List<String> optionType = new ArrayList<String>();
                        optionType.add(OPtion);
                        try {
                            Map<String,Object> orderCount =  yzOrderMapper.findExCount(updOrderMap);
                            if(orderCount!=null){
                                switch (OPtion){
                                    case "PowerOn"://开机
                                        intExCount = orderCount.get("is_boot_exCount")!=null?Integer.parseInt(orderCount.get("is_boot_exCount").toString()):intExCount;
                                        break;
                                    case "OpenNetwork"://开网
                                        intExCount = orderCount.get("is_openNet_exCount")!=null?Integer.parseInt(orderCount.get("is_openNet_exCount").toString()):intExCount;
                                        break;
                                    case "InternetDisconnection"://达量断网 订购
                                        intExCount = orderCount.get("is_dd_exCount")!=null?Integer.parseInt(orderCount.get("is_dd_exCount").toString()):intExCount;
                                        break;
                                }
                            }
                        }catch (Exception e){
                            log.error("intExCount 查询 yz_order 异常 "+e.getMessage());
                        }
                        intExCount +=1;//执行次 +1
                        Map<String,Object> CardDiagnosisMap = new HashMap<>();
                        CardDiagnosisMap.put("source_type", source_type);//变更来源
                        CardDiagnosisMap.put("quota", quota);//阈值MB
                        CardDiagnosisMap.put("updOrderMap", updOrderMap);
                        CardDiagnosisMap.put("optionType",optionType);
                        CardDiagnosisMap.put("iccid",iccid);
                        CardDiagnosisMap.put("exCount",intExCount);
                        plOrder.orderCardDiagnosisSend(CardDiagnosisMap);
                    }
                }
            }else {
                log.info("Diagnosis {} 未划分通道执行 取消 operationArr : {} , quota {} ,  source_type = {}",iccid,JSON.toJSONString(operationArr),quota,source_type);
            }

        }
    }




    /**
     * 开机
     * @param iccid
     * @param Parammap
     * @param map
     */
    public  boolean Open (String iccid,Map<String,Object> Parammap,Map<String,Object> map,Map<String,Object> updOrderMap){
        String status_id = map.get("status_id")!=null &&map.get("status_id").toString().length()>0?map.get("status_id").toString():"未知";
        String cbefore = "";
        if(!status_id.equals("未知")){
            cbefore =  myDictionary.getdictLabel("yunze_card_status_ShowId",status_id);
        }else{
            cbefore = status_id;
        }
        cbefore = cbefore !=null && cbefore != "" && cbefore.length()>0?cbefore:"未知";
        Map<String,Object> Add_Map = new HashMap<>();
        Add_Map.put("iccid",iccid);
        Add_Map.put("ctype","2");//生命周期
        Add_Map.put("cbefore",cbefore);
        Add_Map.put("cafterward","开机");
        Add_Map.put("source_type","4");// 来源 类型 ：4 C端充值

        Map<String,Object> Upd_Map = new HashMap<>();
        Upd_Map.put("status_id","1");
        Upd_Map.put("iccid",iccid);
        boolean  suessBool = cardChange.OnOff(Parammap,map,Add_Map,Upd_Map);
        int is_boot_exStatus = suessBool?1:0;
        Map<String,Object> updMap = new HashMap<>();
        updMap.putAll(updOrderMap);
        updMap.put("is_boot_exStatus",is_boot_exStatus);
        int updCount = yzOrderMapper.updIsInfo(updMap);
        if (updCount>0){
            log.info("订单 开机 执行成功 {}",updMap);
        }else{
            log.error("订单 开机 执行失败 {}",updMap);
        }
        return suessBool;
    }



    /**
     * 开网
     * @param iccid
     * @param Parammap
     * @param map
     */
    public  boolean OpenConnection (String iccid,Map<String,Object> Parammap,Map<String,Object> map,Map<String,Object> updOrderMap){
        String connection_status = map.get("connection_status")!=null &&map.get("connection_status").toString().length()>0?map.get("connection_status").toString():"未知";
        String cbefore = "";
        if(!connection_status.equals("未知")){
            cbefore =  myDictionary.getdictLabel("yz_cardConnection_type",connection_status);
        }else{
            cbefore = connection_status;
        }
        cbefore = cbefore !=null && cbefore != "" && cbefore.length()>0?cbefore:"未知";
        Map<String,Object> Add_Map = new HashMap<>();
        Add_Map.put("iccid",iccid);
        Add_Map.put("ctype","1");//断开网状态
        Add_Map.put("cbefore",cbefore);
        Add_Map.put("cafterward","正常");
        Add_Map.put("source_type","4");// 来源 类型 ：4 C端充值

        Map<String,Object> Upd_Map = new HashMap<>();
        Upd_Map.put("connection_status","1");//正常
        Upd_Map.put("iccid",iccid);
        boolean  suessBool =cardChange.ChangeConnection(Parammap,map,Add_Map,Upd_Map);

        int is_openNet_exStatus = suessBool?1:0;
        Map<String,Object> updMap = new HashMap<>();
        updMap.putAll(updOrderMap);
        updMap.put("is_openNet_exStatus",is_openNet_exStatus);
        int updCount = yzOrderMapper.updIsInfo(updMap);
        if (updCount>0){
            log.info("订单 开网 执行成功 {}",updMap);
        }else{
            log.error("订单 开网 执行失败 {}",updMap);
        }
        return suessBool;
    }


    /**
     * 订购达量断网
     * @param iccid
     * @param Parammap
     * @param map
     */
    public  boolean ByInternetDisconnection (String iccid,Map<String,Object> Parammap,Map<String,Object> map,String source_type,Map<String,Object> updOrderMap){
        String action = Parammap.get("action")!=null &&Parammap.get("action").toString().length()>0?Parammap.get("action").toString():"未知";
        String cbefore = "";
        if(!action.equals("未知")){
            cbefore =  myDictionary.getdictLabel("yz_InternetDisconnection_type",action);
        }else{
            cbefore = action;
        }
        cbefore = cbefore !=null && cbefore != "" && cbefore.length()>0?cbefore:"未知";

        source_type = source_type!=null?source_type:"9";//PC端充 9 给个默认值放置报错
        Map<String,Object> Add_Map = new HashMap<>();
        Add_Map.put("iccid",iccid);
        Add_Map.put("ctype","3");//达量断网订购
        Add_Map.put("cbefore","达量断网订购");
        Add_Map.put("cafterward",cbefore);
        Add_Map.put("source_type",source_type);// 来源 类型 ：PC端充 9 C端充值  4

        Map<String,Object> Upd_Map = new HashMap<>();
        boolean  suessBool = cardChange.ChangeInternetDisconnection(Parammap,map,Add_Map,Upd_Map);
        String quota = Parammap.get("quota")!=null?""+Parammap.get("quota"):"";
        int is_dd_exStatus = suessBool?1:0;
        Map<String,Object> updMap = new HashMap<>();
        updMap.putAll(updOrderMap);
        updMap.put("is_dd_exStatus",is_dd_exStatus);
        updMap.put("is_dd_quota",quota);
        int updCount = yzOrderMapper.updIsInfo(updMap);
        if (updCount>0){
            log.info("订单 订购达量断网 执行成功 {}",updOrderMap);
        }else{
            log.error("订单 订购达量断网 执行失败 {}",updOrderMap);
        }
        return suessBool;
    }




}
